import { Component,ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, LoadingController, Slides,Content, List  } from 'ionic-angular';
import { HttpProvider } from "../../providers/http/http";
import { ThemeableBrowser, ThemeableBrowserOptions, ThemeableBrowserObject} from '@ionic-native/themeable-browser';
import { AppConfig } from '../../app/app.config';
import { UtilsProvider } from '../../providers/utils/utils';

/**
 * Generated class for the ContactPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-contact',
  templateUrl: 'contact.html',
})
export class ContactPage {
  @ViewChild('contentSlides') contentSlides: Slides;
  @ViewChild('menuSlides') menuSlides: Slides;
   //menu 菜单
   menuData = []; 
   menuNum:number = 4;
   isAtTop:boolean = true;//上拉刷新控制
 
   // homeArticles = {"top":[],"shehui":[],"guonei":[],"guoji":[],"yule":[],"tiyu":[],"junshi":[],"keji":[],"caijing":[],"shishang":[]};
   homeArticles = [];
   temphHomeArticles = [];//存储单页数据
   listNum = 20; //一页请求的数据量
   
   //当前选择的菜单下标
   currIndex:number = 0;
   //当前请求的菜单url
   currReqUrl:string;
   //当前菜单的list分页
   currListPage:number;
 
 
   public picture:string;
   public loading; //加载弹框
 
   selectedIndex:number = 0;
 
   constructor(public navCtrl: NavController, private httpProvider:HttpProvider, private utils:UtilsProvider, private themeableBrowser: ThemeableBrowser) {
   }
 
   ionViewDidLoad() {
     this.getHomeMenu();
   }
   onScroll(event:any){
     console.log("hahhhdf")
     console.log("event.target.scrollTop==="+event.target.scrollTop);
     //当滚动距离超过80,下拉刷新组件失效并隐藏
     if(event.target.scrollTop>80){
       // this.isAtTop = false;
     }else{
       // this.isAtTop = true;
     }
   }
 
   //搜索
   items: string[];
   initializeItems() {
     this.items = [
       'Amsterdam',
       'Bogota',
       'Chfdogihfb'
     ];
   }
   ionInput(ev:any) {
     // Reset items back to all of the items
     this.initializeItems();
 
     // set val to the value of the searchbar
     const val = ev.target.value;
 
     // if the value is an empty string don't filter the items
     if (val && val.trim() != '') {
       this.items = this.items.filter((item) => {
         //toLowerCase() 转换小写
         return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
       })
     }
   }
   //菜单
   getHomeMenu() {
     this.httpProvider.GET(AppConfig.homeMenuUrl, (data)=>{
       // console.log("data===="+JSON.stringify(data));
       this.menuData = data.tabs;
       if(this.menuData.length <= 4) {
         this.menuNum = this.menuData.length;
         //禁止silde左右滑动
         this.menuSlides.lockSwipes(true);
       } else {
         this.menuNum = 4;
         //允许silde左右滑动
         this.menuSlides.lockSwipes(false);
       }
       for(var i = 0; i < this.menuData.length; i++) {
         let obj = {'page':1, 'dataArr':[]};
         this.homeArticles.push(obj);
       }
 
       //默认获取第一个分页类型数据
       this.utils.showLoading('加载中...');
       this.getPageType();
     }, (err)=>{
 
     })
   }
 
   //初始列表
   getPageType() {
     this.currReqUrl = this.menuData[this.currIndex]['url'];
     this.currListPage = this.homeArticles[this.currIndex]['page'];
     let url = this.currReqUrl+"?page="+this.currListPage;
     console.log('url==='+url);
     this.httpProvider.GET(url, (res)=>{
       console.log("data====="+JSON.stringify(res));
       // 网络请求成功
       if(res.data == null) {
         this.utils.hideLoading();
         return;
       }
       this.temphHomeArticles = this.homeArticles[this.currIndex]['dataArr'];
       let alldata = res.data;
       this.temphHomeArticles = [];
       console.log("res====="+alldata.length);
       for(var i = 0; i < alldata.length; i++){
         var type = 2;
         // if(i>10) {
         //   type = 2;
         // }
         this.temphHomeArticles.push({
           title:alldata[i].title,
           images:alldata[i].images,//图片3
           author_name: alldata[i].author,
           date: alldata[i].pubtime,
           url: alldata[i].url,
           type:type
         })
       }
       this.homeArticles[this.currIndex]['dataArr'] = this.temphHomeArticles;
       
       // console.log("res====="+this.temphHomeArticles);
       this.utils.hideLoading();
     }, (err)=>{
       this.utils.hideLoading();
     })
   }
 
 
   //页面初始化执行次操作，推荐将复杂的东西要放在ngOnInit()方法里，不要放在构造方法里
   ngOnInit() {
     //ionic 2.0正式版本中，请删除mySlideOptions相关代码。
     // this.mySlideOptions = {
     //   loop: false,
     //   autoplay: false,
     //   initialSlide: 0,
     //   pager: false,
     //   slidesPerView: 5,
     //   paginationHide: true,
     //   paginationClickable: true
     // };
   }
 
   
   //下拉刷新
   doRefresh(refresher) {
     console.log('Begin async operation', refresher);
     setTimeout(() => {
       console.log('Async operation has ended');
       this.currReqUrl = this.menuData[this.currIndex]['url'];
       let url = this.currReqUrl+"?page=1";
       this.getNewArticle(url, 1);
       refresher.complete();
     }, 1000);
   }
   //上拉加载
   doInfinite(infiniteScroll) {
     console.log('Begin async operation', infiniteScroll);
     setTimeout(() => {
       console.log('Async operation has ended');
       this.currReqUrl = this.menuData[this.currIndex]['url'];
       this.currListPage = parseInt(this.homeArticles[this.currIndex]['page']); 
       let url = this.currReqUrl+"?page="+(this.currListPage+1);
       this.getNewArticle(url, 2);
       infiniteScroll.complete();
 
       this.temphHomeArticles = this.homeArticles[this.currIndex]['dataArr'];
       console.log('is show infiniteScroll=='+this.temphHomeArticles.length%this.listNum+"all length=="+this.temphHomeArticles.length)
       if (this.temphHomeArticles.length%this.listNum != 0) {
         infiniteScroll.enable(false);   //没有数据的时候隐藏 
       }
     }, 1000);
   }
 
   //获取新闻信息 refreshType:1下拉加载 2上拉刷新
   getNewArticle(url, refreshType) {
     console.log('url======='+url)
     this.httpProvider.GET(url, (res) => {
       // console.log("data====="+JSON.stringify(res));
       // 网络请求成功
       if(res.data == null) {
         this.utils.hideLoading();
         return;
       }
       this.temphHomeArticles = this.homeArticles[this.currIndex]['dataArr'];
       let alldata = res.data;
       console.log("res====="+alldata.length);
       var type = 2;
       if(refreshType == 1) {
         for(var i = alldata.length-1; i >= 0; i--){
           this.temphHomeArticles.unshift({
             title: alldata[i].title,//标题
             images: alldata[i].images,//图片3
             author_name: alldata[i].author,
             date: alldata[i].pubtime,
             url: alldata[i].url,
             type:type
           })
         }
       } else {
         for(var j = 0; j < alldata.length; j++){
           this.temphHomeArticles.push({
             title: alldata[j].title,//标题
             images: alldata[j].images,//图片3
             author_name: alldata[j].author,
             date: alldata[j].pubtime,
             url: alldata[j].url,
             type:type
           })  
         }
       }
      
       this.homeArticles[this.currIndex]['dataArr'] = this.temphHomeArticles;
       this.homeArticles[this.currIndex]['page'] = res.page;
 
       this.utils.hideLoading();
     }, (err)=>{
       this.utils.hideLoading();
     })
   }
   //点击标题
   onSlideClick(index) {
     this.contentSlides.slideTo(index, 500, false); //新闻页滑动
     this.requestData(index);
   }
   //滑动列表
   slideChanged() {
     this.isAtTop = true;
     let index = this.contentSlides.getActiveIndex();
     if(index > 2) { //菜单滑动
       this.menuSlides.slideTo(index-2, 500, false);
     } else {
       this.menuSlides.slideTo(0, 500, false);
     }
     this.requestData(index);
   }
   requestData(currentIndex) {
     this.currIndex = currentIndex;
     let currArr = this.homeArticles[this.currIndex]['dataArr'];
     // console.log("currArr=="+currArr)
     // this.getHttpService(this.pageContent);
     if(!currArr || currArr.length == 0) {
       this.utils.showLoading('加载中...');
       // this.content.scro
       this.getPageType();
     } else {
       this.temphHomeArticles = currArr;
     }
   }
 
   //打开详情页
   openArticles(event, url) {
     this.navCtrl.push('ArticlePage', {'url':url});
     // this.navCtrl.push('TestPage', {'url':url});
   }
   //直接跳转到网页
   showArticles(event, url) {
     let options:ThemeableBrowserOptions = {
       statusbar: {
         color: '#ffffffff'
       },
       toolbar: {
         height: 44,
         color: '#f0f0f0ff'
       },
       // title: {
       //   color: '#003264ff',
       //   showPageTitle: true
       // },
       backButton: {
         image: 'back',
         imagePressed: 'back_pressed',
         align: 'left',
         event: 'backPressed'
       },
       // forwardButton: {
       //   image: 'forward',
       //   imagePressed: 'forward_pressed',
       //   align: 'left',
       //   event: 'forwardPressed'
       // },
       closeButton: {
         image: 'close',
         imagePressed: 'close_pressed',
         align: 'left',
         event: 'closePressed'
       },
       // customButtons: [
       //   {
       //     image: 'share',
       //     imagePressed: 'share_pressed',
       //     align: 'right',
       //     event: 'sharePressed'
       //   }
       // ],
       menu: {
         image: 'menu',
         imagePressed: 'menu_pressed',
         title: 'Test',
         cancel: 'Cancel',
         align: 'right',
         items: [
           {
             event: 'sharePressed',
             label: '分享'
           },
           {
             event: 'savePressed',
             label: '收藏'
           }
         ]
       },
       backButtonCanClose: true
     };
 
     const browser: ThemeableBrowserObject = this.themeableBrowser.create(url, '_blank', options);
     browser.on('sharePressed').subscribe((data)=>{
       alert('share');
     }, (err)=>{
       alert('share:error');
       console.error('onError');
     })
     browser.on('savePressed').subscribe((data)=>{
 
     }, (err)=>{
       
     })
     /** 传参
      * @param msg 子传父
      */
     // let action = (msg)=>{
     //   return new Promise((resolve, reject)=>{
     //     if(msg!=undefined) {
     //       console.log('get son data:'+msg);
     //       resolve('ok');
     //     } else {
     //       reject(Error('error'));
     //     }
     //   })
     // }
     
     /** 父传子
      * 1.push 传参
      * 2.回到当前界面所在的tab界面
      * 3.回到第一个tab界面
      *  */
     // this.navCtrl.push(NewsDetailPage, { "params": item});
     // this.navCtrl.popToRoot();// 返回当前界面所在的tab界面
     // this,this.navCtrl.parent.select(0);
   }
 
   disableRefresh(event) {
     //列表页左右滑动禁止下拉刷新
     // this.isAtTop = false;
   }
 }
 
